//
//  CourseVM.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/4.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit

class CourseVM {
    
    let disposeBag = DisposeBag()
    var mdArray = [String]()
    var resultData = Variable([String:[Course_list]]())
    private var pageList = [Course_list]()
    
    /// 待上课程列表请求
    ///
    /// - Parameters:
    ///   - version: 0-历史课程 1-待上课程
    ///   - sucessBlock: 成功的请求回调
    func courseRequest(_ version: NSInteger,
                       _ sucessBlock: @escaping()->()) {
        let token = BCAPI.get_user_courses(version: version)
        ApiProvider.request(token, model: CourseModel.self) { [weak self] (data) in
            self?.dataManager(data?.course_list, false)
            sucessBlock()
        }
    }
     /// 搜索
     ///
     /// - Parameters:
     ///   - version:  0-历史课程 1-待上课程
     ///   - course_name: 搜索的名字
     /// - Returns: 返回值并未  只是为了flatMapLatest中的return返回值类型形式
     func search_pages(_ version: NSInteger,
                       _ course_name: String) -> Variable<[String:[Course_list]]> {
        if course_name.count > 0 {
            // 有输入的时候才进行搜索
            let token = BCAPI.search_pages(version: version, course_name: course_name)
            ApiProvider.request(token, model: CourseModel.self) { [weak self] (data) in
                self?.dataManager(data?.course_list, false)
            }
        } else {
            // 无搜索的时候清除数据恢复
            self.mdArray.removeAll()
            self.resultData.value.removeAll()
        }
        // 返回值无用  只是为了flatMapLatest中的return返回值类型形式
        return self.resultData
    }
    
    /// 获取历史课程元数据  就是主要多少页 pages
    ///
    /// - Parameters:
    ///   - version: // 1-压缩 0-非压缩
    ///   - sucessBlock: 成功的请求回调
    func getHistoryPage(_ version: NSInteger,
                        _ sucessBlock: @escaping( _ offset: NSInteger?)->()) {
        let token = BCAPI.get_history_page(version: version)
        ApiProvider.request(token, model: CourseModel.self) { [weak self] (data) in
            self?.pageList.removeAll() // 刷新清除数据
            sucessBlock(data?.pages)
        }
    }
    
    ///  获取历史课程指定页码的课程数据(倒排结构)
    ///
    /// - Parameters:
    ///   - offset: 第几页
    ///   - version: 待看还是回看
    ///   - sucessBlock: 回调
    func getPageCourses(offset: NSInteger,
                        _ version: NSInteger,
                        _ sucessBlock: @escaping()->()) {
        let token = BCAPI.get_page_courses(offset: offset, version: version)
        ApiProvider.request(token, model: CourseModel.self) { [weak self] (data) in
            
            if let list = data?.course_list {
                self?.pageList.append(contentsOf: list)
                self?.dataManager(self?.pageList, true)
            }
            sucessBlock()
        }
    }
    
    // 待观看，回放，搜索的列表请求数据的调整
    fileprivate func dataManager( _ list:[Course_list]?, _ isPageCourses: Bool) {
        guard let data = list else {
            return
        }
        //为m数据赋值日期
        let mdData = data.map { (mode) -> Course_list in
            var m = mode
            m.course_info?.course_time_md = String.getDateFormatString(timeStamp: mode.course_info?.course_time ?? 0, format: .TimeType_Md)
            return m
        }
        //取出所有的时间日期
        var mdSet = Set<String>()
        for model in mdData {
            mdSet.insert(model.course_info?.course_time_md ?? "")
        }
        //排序放到数组里
        var mdArray = [String]()
        mdArray.append(contentsOf: mdSet)
        mdArray = mdArray.sorted(by: { (md1, md2) -> Bool in
            if isPageCourses {
                return md1 > md2 //历史回看数据
            }else {
                return md1 < md2 //待看的数据
            }
        })
        self.mdArray = mdArray
        // 整理最终数据
        var resultData = [String:[Course_list]]()
        for md in mdArray {
            var mList = [Course_list]()
            for mdModel in mdData {
                if md == mdModel.course_info?.course_time_md {
                    mList.append(mdModel)
                }
            }
            resultData[md] = mList
        }
        self.resultData.value = resultData
    }
}
